#define  _CRT_SECURE_NO_WARNINGS 1
#include "slist.h"

ListNode* ListNodeBuy(LTNodeType x)
{
	ListNode* pn = (ListNode*)malloc(sizeof(ListNode));
	if (pn == NULL)
	{
		perror("malloc");
		return NULL;
	}
	pn->data = x;
	pn->prev = NULL;
	pn->next = NULL;
	return pn;
}

ListNode* ListNodeInit()
{
	ListNode* phead = ListNodeBuy(0);
	phead->prev = phead;
	phead->next = phead;
	return phead;
}

void ListNodePrint(ListNode* phead)
{
	ListNode* curr = phead->next;
	while (curr != phead)
	{
		printf(LTNodePrintType, curr->data);
		curr = curr->next;
	}
	printf("\n");
}

void ListNodeInsert( ListNode* pos, LTNodeType x)
{
	assert(pos);

	ListNode* newnode = ListNodeBuy(x);
	ListNode* prev = pos->prev;
	
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListNodeErase(ListNode* phead, ListNode* pos)
{
	assert(pos);
	assert(pos != phead);

	ListNode* prev = pos->prev;
	ListNode* next = pos->next;

	prev->next = next;
	next->prev = prev;

	free(pos);
	pos = NULL;
}

void ListNodePushFront(ListNode* phead, LTNodeType x)
{
	assert(phead);

	ListNodeInsert( phead->next, x);
}

void ListNodePushBack(ListNode* phead, LTNodeType x)
{
	assert(phead);

	ListNodeInsert(phead, x);
}

void ListNodePopFront(ListNode* phead)
{
	assert(phead);

	ListNodeErase(phead, phead->next);
}

void ListNodePopBack(ListNode* phead)
{
	assert(phead);

	ListNodeErase(phead, phead->prev);
}

ListNode* ListNodeFind(ListNode* phead, LTNodeType x)
{
	assert(phead);

	ListNode* curr = phead->next;
	while (curr != phead)
	{
		if (curr->data == x)
			return curr;
		curr = curr->next;
	}
	return NULL;
}